import {
  isArray,
  isFunction,
  isNullOrUnDef,
  isObject,
  isString,
} from "@/utils/is";
import { set } from "lodash-es";
import { ComputedRef, Ref, unref } from "vue";
import { FormProps, FormSchema } from "../types/form";
import { Recordable } from "/#/global";

interface UseFormValuesContext {
  defaultValueRef: Ref<any>;
  getSchema: ComputedRef<FormSchema[]>;
  getProps: ComputedRef<FormProps>;
  formModel: Recordable;
}

export function useFormValues({
  defaultValueRef,
  getSchema,
  formModel,
  getProps,
}: UseFormValuesContext) {
  // 处理表单的值
  function handleFormValues(values: Recordable) {
    console.log(values);
    if (!isObject(values)) {
      return {};
    }
    const res: Recordable = {};
    for (const item of Object.entries(values)) {
      let [, value] = item;
      const [key] = item;
      if (!key || (isArray(value) && value.length === 0) || isFunction(value)) {
        continue;
      }

      // Remove spaces
      if (isString(value)) {
        value = value.trim();
      }
      set(res, key, value);
    }
    return res;
  }

  function initDefault() {
    const schemas = unref(getSchema);
    console.log(schemas);
    const obj: Recordable = {};
    schemas.forEach((item) => {
      const { defaultValue } = item;
      if (!isNullOrUnDef(defaultValue)) {
        obj[item.field] = defaultValue;
        formModel[item.field] = defaultValue;
      }
    });
    defaultValueRef.value = obj;
    console.log(defaultValueRef.value)
  }

  return { handleFormValues, initDefault };
}
